import { filterAuth, getDicByKey } from '@/support/common';
import { PlusOutlined } from '@ant-design/icons';
import { Button, Card, message, Table } from 'antd';
import { connect } from 'dva';
import { routerRedux } from 'dva/router';
import PropTypes from 'prop-types';
import React, { PureComponent } from 'react';
import PateoAuthButtons from '../../../components/common/PateoAuthButtons';
import PateoSearchForm from '../../../components/common/PateoSearchForm';
import Ellipsis from '../../../components/Ellipsis';
import DetailsModal from './detailsModal';
import BindingEditModel from './IPDABindingModel';
import SIMDetailModal from './simCardDetailModal';
import VehicleDetailModal from './vehicleDetailModal';
import MaskText from '@/components/MaskText';

const mapStateToProps = (state: any) => ({
  ipda: state.ipda2,
  loading: state.loading.effects['ipda2/getFetchPage'],
});
let page = '';
class Ipda extends PureComponent<any, any> {
  CollectionsPageRef = React.createRef<any>();

  static contextTypes = {
    permissions: PropTypes.array,
    dicData: PropTypes.any,
  };

  constructor(props: any) {
    super(props);
    this.state = {
      detailsModalVisible: false,
      vinDetailVisible: false,
      simDetailVisible: false,
      ipdaDetailVisible: false,
      tboxDetailModelData: {},
      vinDetailModelData: {},
      simDetailModelData: {},
      ipdaDetailModelData: {},
      formValues: {},
    };
  }

  componentDidMount() {
    const { dispatch } = this.props;
    // console.log('this.context.dicData', this.context.dicData);
    // const a = findDicByCode(this.context.dicData, 'deviceStatus');
    // console.log('aaaaaaaaaa', a);

    dispatch({
      type: 'ipda2/getFetchPage',
      payload: { url: '/ipda/list' },
    });
  }

  componentWillUnmount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'ipda2/initData',
    });
  }
  handleTableChange = (pagination: any, filters: any) => {
    const { dispatch } = this.props;
    const { formValues } = this.state;
    const { current, pageSize } = pagination;
    this.setState({ pagination });
    const params = {
      page: current - 1,
      size: pageSize,
      ...formValues,
      ...filters,
    };

    dispatch({
      type: 'ipda2/getFetchPage',
      payload: { url: '/ipda/list', ...params },
    });
  };
  changeAddModalVisible = (flag: any) => {
    if (flag) {
      //TODO:请求接口刷新数据
      this.setState({
        vinDetailVisible: false,
        detailsModalVisible: false,
        simDetailVisible: false,
      });
    } else {
      this.setState({
        vinDetailVisible: false,
        detailsModalVisible: false,
        simDetailVisible: false,
      });
    }
  };
  handleDetailIPDA = (deviceId: any) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'ipda2/getData',
      payload: { url: `/ipda/findOneDeviceId/${deviceId}` },
      callback: (ipdaDetail: any) => {
        if (ipdaDetail.statusCode === '0') {
          dispatch({
            type: 'ipda2/getDataWithRes',
            payload: { url: '/ipda/findgroup', deviceId },
            callback: (data: any) => {
              if (data.status.code === '200') {
                let obj = Object.assign({}, ipdaDetail);
                let list = data.groups.filter((d: any) => d.deviceType === '2');
                let tbox = '';
                if (list && list.length > 0) {
                  tbox = list[0].deviceId;
                  obj.tbox = tbox;
                }
                this.setState({ ipdaDetailModelData: obj, detailsModalVisible: true });
              }
            },
          });
        } else {
          message.error(ipdaDetail.data.status.description);
        }
      },
    });
  };
  handleDetailVIN = (vin: any) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'ipda2/getDataWithRes',
      payload: { url: `/vehicle/findprofile/${vin}` },
      callback: response => {
        if (response.statusCode === '0') {
          if (response.data) {
            this.setState({ vinDetailModelData: response.data, vinDetailVisible: true });
          }
        } else {
          message.error(response.description);
        }
      },
    });
  };
  handleDetailSIM = deviceId => {
    const { dispatch } = this.props;
    dispatch({
      type: 'ipda2/getDataWithRes',
      payload: { url: `/simcard/findOneDeviceId/${deviceId}` },
      callback: simDetail => {
        if (simDetail.statusCode === '0') {
          this.setState({ simDetailModelData: simDetail.data, simDetailVisible: true });
        } else {
          message.error(simDetail.statusMessage);
        }
      },
    });
  };
  handleBindingData = record => {
    const obj = record;
    obj.page = page;
    obj.formValues = this.state.formValues;

    this.CollectionsPageRef.current?.showModalEdit(obj);
  };
  handleFormReset = () => {
    const { form, dispatch } = this.props;
    form.resetFields();
    this.state.formValues = {};
    dispatch({
      type: 'ipda2/getDataWithRes',
      payload: {},
    });
  };
  handleEditData = deviceId => {
    const { dispatch } = this.props;
    const obj = {};
    obj.pageObj = page;
    obj.values = this.state.formValues;

    dispatch({
      type: 'ipda2/getDataWithRes',

      payload: { url: `/ipda/findOneDeviceId/${deviceId}` },

      callback: (data: any) => {
        if (data.data.deviceId) {
          dispatch(
            routerRedux.push({
              pathname: '/connectPlat/ipda/ipdaEdit',
              flag: true,
              state: { data, obj },
            }),
          );
        } else {
          message.error('获取失败');
        }
      },
    });
  };
  render() {
    const {
      ipda: {
        pageData: { list, pagination },
      },
      loading,
      dispatch,
      location: { pathname = '/' },
    } = this.props;
    page = pagination;
    const { formValues, tbox } = this.state;

    const columns = [
      {
        title: '车机编号',
        dataIndex: 'deviceId',
        render: text => {
          return <a onClick={() => this.handleDetailIPDA(text)}>{text}</a>;
        },
      },
      {
        title: '软件版本号',
        dataIndex: 'versionSoftware',
        render: text => {
          return (
            <Ellipsis length={20} tooltip>
              {text}
            </Ellipsis>
          );
        },
      },
      {
        title: '硬件版本号',
        dataIndex: 'versionHardware',
        render: text => {
          return (
            <Ellipsis length={20} tooltip>
              {text}
            </Ellipsis>
          );
        },
      },
      {
        title: '状态',
        dataIndex: 'deviceStatus',
        render: (text: any) => {
          if (text || text === 0) {
            return getDicByKey(this.context.dicData, 'deviceStatus', text.toString());
          } else {
            return text;
          }
        },
      },
      {
        title: '入库时间',
        dataIndex: 'createDate',
      },
      {
        title: 'VIN号',
        dataIndex: 'vin',
        render: text => {
          return <a onClick={() => this.handleDetailVIN(text)}>{text}</a>;
        },
      },
      {
        title: 'SIM卡号',
        dataIndex: 'sim',
        render: text => {
          return (
            <a onClick={() => this.handleDetailSIM(text)}>
              <MaskText text={text} type="simCard" />
            </a>
          );
        },
      },
      {
        title: '操作',
        dataIndex: '操作',
        width: 200,
        fixed: 'right',
        render: (text: any, record: any) => {
          const editBtn = {
            title: '编辑',
            key: 'edit',
            auth: 'ipda_doEdit',
            onConfirm: () => this.handleEditData.bind(this)(record.deviceId),
          };
          const bindBtn = {
            title: '修改绑定关系',
            key: 'editBinding',
            auth: 'ipda_doAlter',
            onConfirm: () => this.handleBindingData.bind(this)(record),
          };
          const btns = [];
          btns.push(editBtn);
          if (!(record && record.projectId && record.projectId === 'dfspt')) {
            btns.push(bindBtn);
          }
          return <PateoAuthButtons btns={btns} max={1} pathname={pathname} />;
        },
      },
    ];
    const paginationProps = {
      pageSizeOptions: [10, 20, 50],
      showSizeChanger: true,
      showQuickJumper: true,
      ...pagination,
      showTotal: () => (
        <span>共&nbsp;{pagination === undefined ? 0 : pagination.total}&nbsp;条</span>
      ),
    };

    const searchItems = [
      {
        type: 'input',
        title: '车机编号',
        key: 'deviceId',
      },
      {
        type: 'input',
        title: '软件版本',
        key: 'versionSoftware',
      },
      {
        type: 'input',
        title: '硬件版本',
        key: 'versionHardware',
      },
    ];

    return (
      <div>
        <Card bordered={false}>
          <PateoSearchForm
            searchItems={searchItems}
            fetchParams={{ type: 'ipda2/getFetchPage', url: '/ipda/list' }}
            saveFormValues={(val: any) =>
              this.setState({ formValues: Object.assign(formValues, val) })
            }
            handleFormReset={() => this.setState({ formValues: {} })}
          />
        </Card>

        <Card style={{ marginTop: 12 }} bordered={false}>
          {filterAuth('ipdaAdd_add', this.context.permissions, pathname) ? (
            <div className="my_newItem">
              <Button
                size="small"
                icon={<PlusOutlined />}
                type="primary"
                onClick={() => this.props.history.push('/connectPlat/ipda/ipdaAdd')}
              >
                新增
              </Button>
            </div>
          ) : null}
          <Table
            size={'small'}
            rowKey={record => record.sid}
            dataSource={list}
            loading={loading}
            columns={columns}
            pagination={paginationProps}
            onChange={this.handleTableChange}
            scroll={{ x: '150%' }}
          />
        </Card>
        {this.state.detailsModalVisible ? (
          <DetailsModal
            changeAddModalVisible={this.changeAddModalVisible}
            detailModelData={this.state.ipdaDetailModelData}
            dispatch={dispatch}
          />
        ) : null}
        {this.state.vinDetailVisible ? (
          <VehicleDetailModal
            changeAddModalVisible={this.changeAddModalVisible}
            detailModelData={this.state.vinDetailModelData}
            dispatch={dispatch}
          />
        ) : null}
        {this.state.simDetailVisible ? (
          <SIMDetailModal
            changeAddModalVisible={this.changeAddModalVisible}
            detailModelData={this.state.simDetailModelData}
            dispatch={dispatch}
          />
        ) : null}

        <BindingEditModel
          // ref="CollectionsPageRef"
          ref={this.CollectionsPageRef}
          icon="plus"
          type="primary"
          title="修改绑定关系"
          dispatch={this.props.dispatch}
          tbox={tbox}
          resetOutterForm={this.handleFormReset}
        />
      </div>
    );
  }
}
export default connect(mapStateToProps)(Ipda);
